/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.appspot.trafficando.infrastructure.aspect;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;

/**
 *
 * @author Domenico Maria Giffone
 */
public class RetryAspect extends AbstractOrderedAspect {

    private Log log = LogFactory.getLog(getClass());
    private int maxRetries;

    public void setMaxRetries(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    public Object retry(ProceedingJoinPoint jp) throws Throwable {
        int retryCount = 1;
        while (true) {
            try {
                log.debug(retryCount + " execution trial.");
                Object result = jp.proceed();
                log.debug("execution succeed!");
                return result;
            } catch (Throwable e) {
                if (++retryCount > maxRetries) {
                    log.error("Execution failed after the " +  retryCount + " retry with the following error: " + e);
                    throw e;
                }
                log.warn("Execution failed due to error: " + e.getMessage());
            }
        }
    }
}
